package controllers

import config.{MyAwait, Search}
import dao.BlockDao
import javax.inject.Inject
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents}
import utils.TableUtils
import utils.TableUtils.pageForm

import scala.concurrent.ExecutionContext

class AllSearchController @Inject()(blockDao:BlockDao, cc: ControllerComponents)
                                   (implicit exec: ExecutionContext) extends AbstractController(cc) with MyAwait{

  def searchPage(input:String) = Action{implicit request=>
    Ok(views.html.allSearch.searchPage(input))
  }

  def searchByDbInput(input: String) = Action { implicit request =>
    val page = pageForm.bindFromRequest.get
    val option = Array("Gene ID", "Chromosome", "eggNOG OGs", "narr OG name", "narr OG cat", "narr OG desc",
      "best OG name", "best OG cat", "best OG desc", "EC",  "KEGG ko", "KEGG Pathway", "KEGG Module", "KEGG Reaction",
    "KEGG rclass","KEGG BRITE","KEGG TC","GOs","Preferred name","CAZy","BiGG Reaction","PFAMs")

    if (Search.searchMap.getOrElse(input, "") == "") {
      Search.getSearchMap(input)
    }

    Search.searchTimeMap.put(input, System.currentTimeMillis())

    val result = Search.searchMap(input)

    val total = result.size
    val tmpX = result.slice(page.offset, page.offset + page.limit)

    val keys = input.trim.split(" ").map(_.trim)
    val row = tmpX.map { x =>
      val r = Search.search.find(_._1 == x._2).get
      val species = r._2

      val text = r._3.split("\t")
      val result = keys.map { k =>
        val results = text.zipWithIndex.find(_._1.toLowerCase.indexOf(k.toLowerCase) != -1).get
        Json.obj("option" -> option(results._2), "result" -> Search.getKeyWord(results._1, input))
      }.distinct
      val blocks = blockDao.getById(r._1).toAwait

      val b = if(blocks.nonEmpty){
        val block =blocks.head
        val blockHtml =  "<tr><td>" + block.block.split(",").map{bl=>
         val id = bl
          s"<a href='/alfalfa/browse/geneByGeneId/$id' target='_blank'>$bl</a>"
        }.grouped(5).map{q=>
          q.mkString("</td><td>")
        }.mkString("</td></tr><tr><td>") + "</td></tr>"
/*        val bHtml =  block.map(_.geneid).map{q=>
          val bid = TableUtils.geneIdToID(q)
          s"<a href='/SGB/db/geneInfo/page/$bid' target='_blank'>$q</a>"
        }.mkString*/

        Json.obj("isBlock" -> "true",/*"tomato" -> bHtml,*/"block" -> blockHtml)
      }else{
        Json.obj("isBlock" -> "false")
      }

      Json.obj("id" -> r._1, "geneid" -> text.head, "species" -> species,"speciesId" -> x._1, "result" -> result,"block" -> b)
    }

    Ok(Json.obj("rows" -> row, "total" -> total))
  }


}
